package logic

import (
	"api/model/order_food_goods"
	"api/service"
	"context"
	"github.com/zeromicro/go-zero/core/stores/sqlx"

	"api/internal/svc"
	"api/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type OrderFoodGoodsUpdateLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewOrderFoodGoodsUpdateLogic(ctx context.Context, svcCtx *svc.ServiceContext) *OrderFoodGoodsUpdateLogic {
	return &OrderFoodGoodsUpdateLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *OrderFoodGoodsUpdateLogic) OrderFoodGoodsUpdate(req *types.RequestOrderFoodGoodsUpdate) (resp *types.ResponseMsg, err error) {
	conn := sqlx.NewMysql(l.svcCtx.Config.DataSource)
	goodsModel := order_food_goods.NewOrderFoodGoodsModel(conn)

	busService := service.NewBusinessService(l.ctx, l.svcCtx)
	bus := busService.GetLoginBusinessInfo()

	goods, _ := goodsModel.FindOne(l.ctx, req.Id, bus.Id)
	if goods != nil {
		goods.CategoryId = req.CategoryId
		goods.Title = req.Title
		goods.Price = req.CategoryId
		goods.Img = req.Img
		goods.Amount = req.CategoryId
		goods.BusinessId = bus.Id
		goods.Specifications = req.Specifications
		goods.Properties = req.Properties
		goods.Jialiao = req.Jialiao
		goods.Des = req.Des

		err = goodsModel.Update(l.ctx, goods)

		if err != nil {
			return service.ReturnError()
		}

		if goods.Status == 1 {
			// 保存商品至redis
			redis := l.svcCtx.RedisPool.Get()
			defer redis.Close()
			goodsService := service.NewOrderFoodService(l.ctx, l.svcCtx)

			goodsService.SaveGoods(redis, bus.Id, req.CategoryId, &service.OrderFoodGoods{
				Id:             req.Id,
				Title:          req.Title,
				Price:          req.Price,
				Img:            req.Img,
				Specifications: req.Specifications,
				Properties:     req.Properties,
				Jialiao:        req.Jialiao,
				Des:            req.Des,
			})
		}
	}

	return service.ReturnOk()
}
